<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import infoApi from "@/api/info.js"
import axios from "axios";

const url = ref('')
const info = ref(null)

const fetchInfo = async () => {
  if (!url.value) {
    ElMessage.warning('请输入网址')
    return
  }

  try {
    const response = await infoApi.getWebsiteInfo(url.value.trim())
    info.value = response.data
    ElMessage.success('获取成功')
  } catch (error) {
    console.error(error)
    ElMessage.error('获取失败，请检查网址是否正确')
  }
}

const copyToClipboard = async (text, label = '内容') => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success(`${label}已复制`)
  } catch {
    ElMessage.error(`复制${label}失败`)
  }
}

const copyJson = () => {
  if (!info.value) return
  const json = JSON.stringify({
    icon: info.value.iconLink,
    title: info.value.title,
    description: info.value.description
  }, null, 2)
  copyToClipboard(json, 'JSON')
}

function downloadImage(imageUrl) {
  axios({
    method: 'get',
    url: `/file/download?imageUrl=${imageUrl}`,
    responseType: 'blob',  // 重要：告诉 axios 这是二进制数据
  }).then(response => {
    console.log('文件:',response);
    // 从响应头获取文件名（后端设置了 Content-Disposition）
    const disposition = response.headers['content-disposition'];
    console.log('Content-Disposition:', disposition);

    let fileName = 'downloaded_file';
    if (disposition && disposition.includes('filename=')) {
      fileName = decodeURIComponent(disposition.split('filename=')[1].replace(/"/g, ''));
    }


    // 创建 Blob 对象并触发下载
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);  // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);  // 释放资源
  }).catch(error => {
    console.error("下载失败", error);
  });
}

</script>

<template>
  <div class="app">
    <h1>网址信息提取器</h1>

    <div class="input-area">
      <el-input
          @keyup.enter="fetchInfo"
          v-model="url"
          placeholder="请输入网址，例如 https://baidu.com"
          clearable
          style="width: 400px;"
      />
      <el-button type="primary" @click="fetchInfo" style="margin-left: 10px;">
        获取信息
      </el-button>
    </div>

    <div v-if="info" class="info-card">
      <el-card>
        <div class="info-row">
          <img :src="info.iconLink" alt="图标" v-if="info.iconLink" class="icon"/>
          <el-button v-if="info.iconLink" type="text" @click="copyToClipboard(info.iconLink, '图标链接')">
            复制图标链接
          </el-button>
          <!-- 图标下载按钮 -->
            <el-button type="text" icon="el-icon-download"  @click="downloadImage(info.iconLink)">下载图标</el-button>
        </div>

        <div class="info-row">
          <strong>标题：</strong> {{ info.title || '无标题' }}
          <el-button type="text" @click="copyToClipboard(info.title || '', '标题')">
            复制标题
          </el-button>
        </div>

        <div class="info-row">
          <strong>描述：</strong> {{ info.description || '无描述' }}
          <el-button type="text" @click="copyToClipboard(info.description || '', '描述')">
            复制描述
          </el-button>
        </div>

      </el-card>

      <!-- JSON 数据展示与复制按钮 -->
      <div v-if="info" class="json-info">
        <el-button type="primary" @click="copyToClipboard(JSON.stringify(info))">
          复制 JSON 信息
        </el-button>
        <pre>{{ JSON.stringify(info, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<style scoped>
.app {
  padding: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.input-area {
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-input {
  max-width: 400px;
}

.el-button {
  margin-left: 10px;
}

.info-card {
  width: 600px;
  margin-top: 20px;
}

.el-card {
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.info-row {
  margin: 15px 0;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  font-size: 16px;
}

.icon {
  width: 48px;
  height: 48px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 4px;
  background-color: #fff;
}

.json-info {
  margin-top: 20px;
  background-color: #f3f4f6;
  padding: 16px;
  border-radius: 8px;
  font-family: monospace;
  font-size: 14px;
  max-height: 300px;
  overflow: auto;
  box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.05);
}

</style>
